package com.xiaominge.utils.wordUtils;

import com.xiaominge.exception.ParameterRuntimeException;
import fr.opensagres.poi.xwpf.converter.pdf.PdfConverter;
import fr.opensagres.poi.xwpf.converter.pdf.PdfOptions;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

import java.io.*;

/**
 * @program: system_platform
 * @description: word 转pdf
 * @author: xiaominge
 * @create: 2020-12-30 14:50
 **/
@Slf4j
public class WordToPdfUtils {
    private WordToPdfUtils() {
    }

    private static WordToPdfUtils wordToPdfUtils;

    public static WordToPdfUtils getUtils() {
        if (wordToPdfUtils == null) {
            synchronized (WordToPdfUtils.class) {
                if (wordToPdfUtils == null) {
                    wordToPdfUtils = new WordToPdfUtils();
                }
            }
        }
        return wordToPdfUtils;
    }


    /**
     * 多克斯为pdf
     *
     * @param wordInputStream 字输入流
     * @param pdfOutputStream pdf输出流
     *                        当前方法有一个问题 空字符串会被主动加入空格  源码问题
     *                           Chunk chunk = createTextChunk( textContent.isEmpty() ? " " : sbuf.toString(), pageNumber, chunkFont,
     *                                        underlinePatterns, backgroundColor );
     */

    public void docxToPdf(InputStream wordInputStream, OutputStream pdfOutputStream) {
        if (wordInputStream == null) {
            ParameterRuntimeException.throwException("word文件流为空");
        }
        try {
            XWPFDocument xwpfDocument = new XWPFDocument(wordInputStream);
          PdfConverter.getInstance().convert(xwpfDocument, pdfOutputStream, PdfOptions.create());

            wordInputStream.close();
            pdfOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
            ParameterRuntimeException.throwException("读取word文件失败,只支持docx文件");
        }
    }

    public static void main(String[] args) throws FileNotFoundException {
        WordToPdfUtils.getUtils().docxToPdf(new FileInputStream("D:/桌面/卷内文件1002247741864148992.docx"), new FileOutputStream("D:/桌面/test.pdf"));
    }


}
